package com.jybd.live.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.live.model.v20161101.AddLiveRecordNotifyConfigRequest;
import com.aliyuncs.live.model.v20161101.AddLiveRecordNotifyConfigResponse;
import com.aliyuncs.live.model.v20161101.DeleteLiveRecordNotifyConfigRequest;
import com.aliyuncs.live.model.v20161101.DeleteLiveRecordNotifyConfigResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jybd.live.dao.RecordDao;
import com.jybd.live.model.Record;
import com.jybd.live.service.AliLiveService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.URL;
import java.util.Date;

@Service
public class AliLiveServiceImpl implements AliLiveService {

    @Value("${ALI.ACCESS_KEY_ID}")
    private String ACCESS_KEY_ID;
    @Value("${ALI.ACCESS_SECRET}")
    private String ACCESS_SECRET;
    @Value("${ALI.BUCKET_NAME}")
    private String BUCKET_NAME;
    @Value("${ALI.END_POINT}")
    private String END_POINT;
    @Value("${ALI.LIVE_RECORD_NOTIFICATION}")
    private boolean LIVE_RECORD_NOTIFICATION;

    //log4j2日志
    private Logger log = LoggerFactory.getLogger(this.getClass());
    //阿里直播客户端
    private DefaultAcsClient acsclient;
    //阿里oss存储服务客户端
    private OSS ossClient;

    private RecordDao recordDao;

    @Autowired
    public AliLiveServiceImpl(RecordDao recordDao) {
        this.recordDao = recordDao;
    }

    /**
     * 初始化方法
     */
    @PostConstruct
    public void initClient() {

        /**
         * 初始化直播 连接
         */
        IClientProfile profile = DefaultProfile.getProfile("cn-shenzhen", ACCESS_KEY_ID, ACCESS_SECRET);
        acsclient = new DefaultAcsClient(profile);
        //注册阿里的录制回调监听
        addLiveRecordNotification();
        /**
         * 初始化oss连接
         */
        // 创建OSSClient实例。
        ossClient = new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_SECRET);
    }


    @Override
    public boolean addLiveRecordNotification() {
        if(!LIVE_RECORD_NOTIFICATION){
            return false;
        }
        log.info("init method called addLiveRecordNotification() ");
        AddLiveRecordNotifyConfigRequest liveRecordNotifyConfigRequest = new AddLiveRecordNotifyConfigRequest();
        liveRecordNotifyConfigRequest.setDomainName("pull.ruitianbuilding.com");
        liveRecordNotifyConfigRequest.setSysProtocol(ProtocolType.HTTPS);
        liveRecordNotifyConfigRequest.setAcceptFormat(FormatType.JSON);
        liveRecordNotifyConfigRequest.setNotifyUrl("http://106.75.251.172:8080/aliCallBack/rec");
        try {
            AddLiveRecordNotifyConfigResponse response = acsclient.getAcsResponse(liveRecordNotifyConfigRequest);
            log.info(new ObjectMapper().writeValueAsString(response));
            return true;
        } catch (ServerException e) {
            log.error(e.getMessage());
        } catch (ClientException e) {
            log.error(e.getMessage());
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
        }
        return false;
    }

    @Override
    public boolean deleteLiveRecordNotification() {
        if(!LIVE_RECORD_NOTIFICATION){
            return false;
        }
        log.info("deleteLiveRecordNotification method receive called");
        DeleteLiveRecordNotifyConfigRequest request = new DeleteLiveRecordNotifyConfigRequest();
        request.setDomainName("pull.ruitianbuilding.com");
        try {
            DeleteLiveRecordNotifyConfigResponse response = acsclient.getAcsResponse(request);
            log.info(new ObjectMapper().writeValueAsString(response));
            return true;
        } catch (ClientException e) {
            log.error(e.getMessage());
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
        }
        return false;
    }

    @Override
    public String getLiveRecordURL(String path) {
        try {
            String objectName = path;
            // 设置URL过期时间为1小时。
            Date expiration = new Date(new Date().getTime() + 3600 * 1000);
            // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
            URL url = ossClient.generatePresignedUrl(BUCKET_NAME, path, expiration);
            return url.toString();
        } catch (com.aliyun.oss.ClientException e) {
            log.error(e.getMessage());
            return null;
        }
    }

    @Override
    public boolean insertRecord(Record record) {
        return recordDao.insert(record);
    }

    @PreDestroy
    /**
     * 释放前 解除监听注册 关闭资源连接
     */
    public void preDestroy() {
        log.info("will call deleteLiveRecordNotification method before destory");
        deleteLiveRecordNotification();
        // 关闭直播client
        acsclient.shutdown();
        // 关闭OSSClient。
        ossClient.shutdown();
    }

}
